"""
学员管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.student import Student
from app.schemas.student import StudentCreate, StudentUpdate, StudentResponse
from app.api.deps import get_current_active_user

router = APIRouter()


@router.get("/")
def get_students(
    db: Session = Depends(get_db),
    page: int = 1,
    size: int = 20,
    name: str = None,
    phone: str = None,
    status: str = None,
    # current_user: Any = Depends(get_current_active_user)  # 临时移除认证要求
) -> Any:
    """
    获取学员列表
    """
    query = db.query(Student)
    
    # 添加搜索条件
    if name:
        query = query.filter(Student.name.contains(name))
    if phone:
        query = query.filter(Student.phone.contains(phone))
    if status:
        query = query.filter(Student.status == status)
    
    # 计算总数
    total = query.count()
    
    # 分页
    skip = (page - 1) * size
    students = query.offset(skip).limit(size).all()
    
    # 将SQLAlchemy模型转换为字典
    students_data = []
    for student in students:
        student_dict = {
            "id": student.id,
            "name": student.name,
            "gender": student.gender,
            "phone": student.phone,
            "email": student.email,
            "province": student.province,
            "source": student.source,
            "status": student.status,
            "created_at": student.created_at.isoformat() if student.created_at else None,
            "updated_at": student.updated_at.isoformat() if student.updated_at else None
        }
        students_data.append(student_dict)
    
    return {
        "items": students_data,
        "total": total,
        "page": page,
        "size": size
    }


@router.get("/{student_id}", response_model=StudentResponse)
def get_student(
    student_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取单个学员信息
    """
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学员不存在"
        )
    return student


@router.post("/", response_model=StudentResponse)
def create_student(
    *,
    db: Session = Depends(get_db),
    student_in: StudentCreate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    创建新学员
    """
    # 检查手机号是否已存在
    existing_student = db.query(Student).filter(
        Student.phone == student_in.phone
    ).first()
    if existing_student:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="手机号已存在"
        )
    
    student = Student(**student_in.dict())
    db.add(student)
    db.commit()
    db.refresh(student)
    return student


@router.put("/{student_id}", response_model=StudentResponse)
def update_student(
    *,
    db: Session = Depends(get_db),
    student_id: int,
    student_in: StudentUpdate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    更新学员信息
    """
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学员不存在"
        )
    
    # 如果更新手机号，检查是否重复
    if student_in.phone and student_in.phone != student.phone:
        existing_student = db.query(Student).filter(
            Student.phone == student_in.phone
        ).first()
        if existing_student:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="手机号已存在"
            )
    
    update_data = student_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(student, field, value)
    
    db.add(student)
    db.commit()
    db.refresh(student)
    return student


@router.delete("/{student_id}")
def delete_student(
    *,
    db: Session = Depends(get_db),
    student_id: int,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    删除学员
    """
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学员不存在"
        )
    
    db.delete(student)
    db.commit()
    return {"message": "学员删除成功"}
